//  Inside Microsoft Exchange 2007 Web Services 
//  Chapter 19
//
//  Copyright (c) 2007 David Sterling, Ben Spain, Mark Taylor, Huw Upshall, Michael Mainer.  
//  All rights reserved.
//

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Principal;
using System.Web;
using System.Threading;

namespace GettingTheUsersSid
{
    class Program
    {
        static void Main(string[] args)
        {
            // normal thread account
            //
            GetCurrentUsersSid();

            // ASP.Net calling account
            //
            if (HttpContext.Current != null)
            {
                GetCurrentCallersSid();
            }
        }

        /// <summary>
        /// Get the current user's sid (Listing 19-4)
        /// </summary>
        /// <returns>Sid</returns>
        /// 
        public static SecurityIdentifier GetCurrentUsersSid()
        {
            AppDomain.CurrentDomain.SetPrincipalPolicy(
                               PrincipalPolicy.WindowsPrincipal);
            WindowsIdentity currentUser = Thread.CurrentPrincipal.Identity as
                               WindowsIdentity;
            SecurityIdentifier sid = currentUser.User;
            Console.WriteLine("The current user's sid in SDDL format is: " +
                          sid.ToString());
            return sid;
        }

        /// <summary>
        /// Get the sid of the current authenticated ASP.Net caller (Listing 19-5)
        /// </summary>
        /// <returns>Sid of current caller</returns>
        /// 
        public static SecurityIdentifier GetCurrentCallersSid()
        {
            WindowsIdentity caller = HttpContext.Current.User.Identity as
                                         WindowsIdentity;
            return caller.User;
        }
    }
}
